package com.qf.hospital.system.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import java.io.Serializable;

@Component
public class RedisDefaultWebSessionManager extends DefaultWebSessionManager {


    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        // 获取sessionId
        Serializable sessionId = getSessionId(sessionKey);
        if (sessionId == null) {
            return null;
        }
        ServletRequest request = null;
        // 去redis之前,先去request域
        if(sessionKey instanceof WebSessionKey){
            WebSessionKey webSessionKey = (WebSessionKey) sessionKey;
            request = webSessionKey.getServletRequest();
            Session s = (Session) request.getAttribute(sessionId + "");
            if (s != null){
                return s;
            }
        }

        // 去redis找session
        Session s = retrieveSessionFromDataSource(sessionId);

        if (s == null) {
            //session ID was provided, meaning one is expected to be found, but we couldn't find one:
            String msg = "Could not find session with ID [" + sessionId + "]";
            throw new UnknownSessionException(msg);
        }
        // 放request一份
        request.setAttribute(sessionId + "",s);
        return s;
    }
}
